#include "xpmio.h"
#include "lsystem.h"
#include "lines.h"

void expand(Lsystem_t sysinfo, char* start, int num_iters, char* result) {
	int i, j, len;
	char buffer1[2048];
	char buffer2[2048];
	char* tmp = start;
	char* successor;
	char* writeto = buffer1;

	buffer1[0] = buffer2[0] = '\0';

	for(j = 0; j < num_iters; j++) {
		len = strlen(tmp);
		for(i = 0; i < len; i++) {
			successor = getSuccessor(sysinfo, tmp[i]);
			if(strlen(successor) > 0) {
				strcat(writeto, successor);
			}
			else {
				strncat(writeto, tmp+i, 1);
			}
		}

		printf("%d: %s\n", j, buffer2);

		if(j != num_iters-1) {
			if(j % 2 == 0) {
				tmp = buffer1;
				writeto = buffer2;
			}
			else {
				tmp = buffer2;
				writeto = buffer1;
			}

			writeto[0] = 0;
		}
	}

	printf("%s\n", writeto);
	strcpy(result, writeto);
}

void drawLsystem(Lsystem_t sysinfo, char* system) {

	int i, j;
	float x = 0;
	float y = 1023;
	float theta = 0;
	double** img;
	int len = strlen(system);

	img = malloc(sizeof(double*)*2048);

	for(i = 0; i < 2048; i++) {
		img[i] = malloc(sizeof(double)*2048);
		for(j = 0; j < 2048; j++) {
			img[i][j] = 0;
		}
	}

	for(i = 0; i < len; i++) {
		if(isMove(sysinfo, system[i])) {
			movePoint(&x, &y, 10, theta);
		}
		else if(isDraw(sysinfo, system[i])) {
			//printf("drawing at %f %f\n", x, y);
			drawLine(&x, &y, 10, theta, img);
		}
		else if(system[i]  == '[') {
		}
		else if(system[i] == ']') {
		}
		else {
			theta += PI*getAngle(sysinfo, system[i])/180.0;
			//printf("theta: %f\n", theta);
		}
	}

	writeXPM(img, 2048, 2048, "test.xpm");
	
}

main(int argc, char** argv) {
	int num_iters;
	char result[2048];

	printf("Reading sysinfo...\n");
	Lsystem_t sysinfo = readSystem();
	printf("Done reading sysinfo...\n\n");
	printLsystem(sysinfo);

	num_iters = atoi(argv[1]);

	expand(sysinfo, sysinfo.start, num_iters, result);
	printf("%d\n%s\n", strlen(result),result);
	drawLsystem(sysinfo, result);

	return 0;
}
